package org.example.pims.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import org.example.commons.config.MiniProgramUserProperties;
import org.example.commons.constant.Constants;
import org.example.commons.entity.SysHealthStatus;
import org.example.commons.entity.SysUser;
import org.example.commons.enums.HealthStatusEnum;
import org.example.commons.vo.ResultVO;
import org.example.user.manage.form.SysUserForm;
import org.example.user.manage.service.ISysUserService;
import org.example.user.manage.service.ISysHealthStatusService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * 可以通过匿名访问的api
 *
 * @author bothin
 */
@RestController
@RequestMapping("/api/anonymous")
public class AnonymousController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysHealthStatusService healthStatusService;

    @Autowired
    private MiniProgramUserProperties miniProgramUserProperties;

    private RestTemplate restTemplate = new RestTemplate();


    /**
     * 判断该电话是否被住房注册
     * @param phone 电话
     * @return ResultVO
     */
    @GetMapping("/user/phone/judge")
    public ResultVO judgeUserPhone(@RequestParam("phone") String phone){
        SysUser user = userService.findByPhone(phone);
        boolean result = false;
        if (Objects.nonNull(user)){
            result = true;
        }
        return ResultVO.success(result);
    }

    /**
     * 用于微信小程序端注册住户账号
     * @param user 住户
     * @return ResultVO
     */
    @PostMapping("/user/register")
    @Transactional
    public ResultVO registerSysUser(@RequestBody SysUserForm userForm){
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userForm,user);
        if(Objects.isNull(userService.findByOpenid(user.getOpenid()))){
            SysUser sysUser = userService.insert(user);
            return ResultVO.success(sysUser);
        }
        return ResultVO.error("你已经这个微信号已经注册过账号了，可以尝试一键登录");
    }

    /**
     *
     * @param code
     * @return resultVO data: {"session_key":"XYnH3hLrUriMZqufAKhqug==","openid":"oyMxL5HQIlHbqJ72qUNyD55Ltqx8"}
     *                  isRegister: true 表示已经注册  false 表示未有注册
     * @throws JsonProcessingException
     */
    @GetMapping("/wx/openid/user")
    public ResultVO getUserOpenid(@RequestParam(name = "code") String code) throws JsonProcessingException {
        String json = getOpenid(code, miniProgramUserProperties.getAppId(), miniProgramUserProperties.getAppSecret());
        JsonNode jsonNode = Constants.MAPPER.readTree(json);
        ResultVO resultVO = ResultVO.success(json);
        String openid = jsonNode.get("openid").asText();
        boolean isRegister = true;
        if(Objects.isNull(userService.findByOpenid(openid))){
            isRegister = false;
        }
        resultVO.put("isRegister",isRegister);
        return resultVO;
    }


    /**
     * {"session_key":"XYnH3hLrUriMZqufAKhqug==","openid":"oyMxL5HQIlHbqJ72qUNyD55Ltqx8"}
     * @param code
     * @param appId
     * @param appSecret
     * @return
     */
    public String getOpenid(String code, String appId, String appSecret){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + appSecret
                + "&js_code=" + code
                + "&grant_type=authorization_code";
        return restTemplate.getForObject(url, String.class);
    }

}
